<template>
  <div class="canvas-renderer" 
       @mousedown="handleCanvasMouseDown"
       @mousewheel="handleMouseWheel">
    <canvas ref="canvasRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue'
import { useCanvasStore, useElementStore } from '@/store'
import { CanvasElement, ElementType, ShapeType } from '@/types'

const canvasRef = ref<HTMLCanvasElement | null>(null)
const canvasStore = useCanvasStore()
const elementStore = useElementStore()

// 初始化Canvas
const initCanvas = () => {
  if (!canvasRef.value) return
  const canvas = canvasRef.value
  // 设置Canvas尺寸为屏幕大小
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight

  // 监听窗口 resize，同步Canvas尺寸
  window.addEventListener('resize', () => {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    renderCanvas()
  })
}

// 绘制Canvas（核心渲染逻辑，成员B后续完善）
const renderCanvas = () => {
  if (!canvasRef.value) return
  const canvas = canvasRef.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 应用画布缩放和偏移（实现无限画布）
  ctx.save()
  ctx.translate(canvas.width / 2 + canvasStore.panX, canvas.height / 2 + canvasStore.panY)
  ctx.scale(canvasStore.zoom, canvasStore.zoom)

  // 遍历所有元素并绘制
  Object.values(elementStore.elements).forEach(element => {
    drawElement(ctx, element)
  })

  ctx.restore()
}

// 绘制单个元素（成员B完善）
const drawElement = (ctx: CanvasRenderingContext2D, element: CanvasElement) => {
  switch (element.type) {
    case ElementType.SHAPE:
      drawShape(ctx, element)
      break
    case ElementType.IMAGE:
      drawImage(ctx, element)
      break
    case ElementType.TEXT:
      drawText(ctx, element)
      break
    default:
      break
  }
}

// 绘制图形（成员B完善）
const drawShape = (ctx: CanvasRenderingContext2D, element: Extract<CanvasElement, { type: ElementType.SHAPE }>) => {
  ctx.save()
  // 设置图形属性
  ctx.fillStyle = element.background
  ctx.strokeStyle = element.borderColor
  ctx.lineWidth = element.borderWidth

  // 根据图形类型绘制
  switch (element.shapeType) {
    case ShapeType.RECT:
      ctx.fillRect(element.x, element.y, element.width, element.height)
      ctx.strokeRect(element.x, element.y, element.width, element.height)
      break
    case ShapeType.ROUNDED_RECT:
      // 圆角矩形（后续完善，暂用矩形占位）
      ctx.fillRect(element.x, element.y, element.width, element.height)
      ctx.strokeRect(element.x, element.y, element.width, element.height)
      break
    case ShapeType.CIRCLE:
      // 圆形（x,y为左上角，需转换为圆心坐标）
      const cx = element.x + element.width / 2
      const cy = element.y + element.height / 2
      const radius = element.width / 2
      ctx.beginPath()
      ctx.arc(cx, cy, radius, 0, Math.PI * 2)
      ctx.fill()
      ctx.stroke()
      break
  }
  ctx.restore()
}

// 绘制图片（成员B完善）
const drawImage = (ctx: CanvasRenderingContext2D, element: Extract<CanvasElement, { type: ElementType.IMAGE }>) => {
  ctx.save()
  // 应用滤镜
  ctx.filter = element.filter
  // 后续完善：加载Base64图片并绘制
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(element.x, element.y, element.width, element.height)
  ctx.strokeStyle = '#ccc'
  ctx.strokeRect(element.x, element.y, element.width, element.height)
  ctx.fillStyle = '#999'
  ctx.font = '14px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillText('图片占位', element.x + element.width / 2, element.y + element.height / 2)
  ctx.restore()
}

// 绘制文本（成员C完善）
const drawText = (ctx: CanvasRenderingContext2D, element: Extract<CanvasElement, { type: ElementType.TEXT }>) => {
  ctx.save()
  // 后续完善：解析Delta格式并绘制文本
  ctx.fillStyle = element.defaultStyle.color
  ctx.font = `${element.defaultStyle.fontSize}px ${element.defaultStyle.fontFamily}`
  ctx.fillRect(element.x, element.y, element.width, element.height)
  ctx.strokeStyle = '#ccc'
  ctx.strokeRect(element.x, element.y, element.width, element.height)
  ctx.fillStyle = element.defaultStyle.color
  ctx.textAlign = 'left'
  ctx.textBaseline = 'top'
  ctx.fillText('文本占位（双击编辑）', element.x + 10, element.y + 10)
  ctx.restore()
}

// 画布鼠标按下事件（成员B后续完善拖拽逻辑）
const handleCanvasMouseDown = (e: MouseEvent) => {
  console.log('画布鼠标按下', e)
  // 后续添加拖拽画布、选中元素逻辑
}

// 鼠标滚轮事件（成员B完善缩放逻辑）
const handleMouseWheel = (e: WheelEvent) => {
  e.preventDefault()
  // 后续添加缩放逻辑
}

// 初始化Canvas
onMounted(() => {
  initCanvas()
  renderCanvas()
})

// 监听画布状态或元素变化，触发重绘
watchEffect(() => {
  renderCanvas()
})
</script>

<style scoped>
.canvas-renderer {
  width: 100%;
  height: 100%;
  cursor: grab;
}

.canvas-renderer:active {
  cursor: grabbing;
}
</style>